package com.devicemantra.coordinate.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class SettingsDAOImpl implements SettingsDAO {
	private SessionFactory sessionFactory;

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public void save(final Settings settings) {
		final Session session = sessionFactory.getCurrentSession();
		try {
			session.save(settings);
		} catch (final HibernateException e) {
			System.out.println(e);
		}
	}

	@Transactional
	public void update(final Settings settings) {
		final Session session = sessionFactory.getCurrentSession();
		final String queryString = "update Settings set "
				+ "eppdPassword = :neweppdPassword, " + "eppdIp = :neweppdIp, "
				+ "eppdPort = :neweppdPort, "
				+ "extensions = :neweppdExtensions "
				+ " where friendlyName = :neweppdFriendlyName ";
		System.out.println("Query " + queryString);
		final Query customQuery = session.createQuery(queryString);

		try {
			customQuery
					.setString("neweppdPassword", settings.getEppdPassword());
			customQuery.setString("neweppdIp", settings.getEppdIp());
			customQuery.setString("neweppdPort", settings.getEppdPort());
			customQuery
					.setString("neweppdExtensions", settings.getExtensions());
			customQuery.setString("neweppdFriendlyName",
					settings.getFriendlyName());
			customQuery.executeUpdate();
			session.flush();
		} catch (final HibernateException e) {
			System.out.println(e);
		}
	}

	@Transactional
	public Settings getSetting(final String eppdServerName) {
		List<Settings> eppdServerlist = null;
		Settings settings = null;
		final Session session = sessionFactory.getCurrentSession();
		final Query query = session
				.createQuery("from Settings where friendlyName = :name");
		query.setParameter("name", eppdServerName);
		eppdServerlist = query.list();
		if (eppdServerlist != null && eppdServerlist.size() > 0) {
			settings = eppdServerlist.get(0);
		}
		return settings;
	}

	@Transactional
	public List<Settings> getAllSettings() {
		final Query query = sessionFactory.getCurrentSession().createQuery(
				"from Settings ");
		return query.list();
	}

	@Transactional
	public void delete(final String eppServerName) {
		final Session session = sessionFactory.getCurrentSession();
		final String queryString = "delete from Settings where friendlyName = :friendlyName";
		System.out.println("Query " + queryString);
		final Query customQuery = session.createQuery(queryString);

		try {
			customQuery.setString("friendlyName", eppServerName);
			customQuery.executeUpdate();
			session.flush();
		} catch (final HibernateException e) {
			System.out.println(e);
		}
	}

	public void setSessionFactory(final SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
}
